package parseur_graphique;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;

import java.util.ArrayList;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;

import org.xml.sax.SAXException;

import projet.*;
import projet.Process;
import exceptions.*;

public class WorkshopGUI extends JPanel implements ActionListener {

        private static final long serialVersionUID = 1L;

        protected String path = "/home/florian/Images/";

        static Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();

        static private final int pictureWpx = 600;

        static private final int pictureHpx = 400;

        private JButton buttonLoad;
        private JButton buttonCalcul;
        private JButton buttonClose;

        private JPanel titlePanel;

        private JPanel centerPanel;

        private JPanel buttonPanel;

        private JPanel eastPanel;

        private JPanel westPanel;

        private static JTextArea contents = new JTextArea();;

        private JScrollPane scrollPane;

        private JComboBox comboBoxPieces;

        private JFileChooser fc;
       
       
        Workshop myWorkshop ;

        public WorkshopGUI() throws Exception {
                JPanel myPanel = new JPanel(new BorderLayout());
                fc = new JFileChooser();
                // Upper part which contains title and name of current workshop.
                titlePanel = new JPanel();
                // Middle of the panel, containing image.
                centerPanel = new JPanel();
                // Lower part which contains buttons used for loading and closing
                // information about a workshop.
                buttonPanel = new JPanel();
                // Right part containing pieces and button which invokes price
                // calculation.
                eastPanel = new JPanel(new GridLayout(15, 1));
                // Left part which contains informations about a workshop, once it has
                // been loaded.
                westPanel = new JPanel();

                // Add components:
                JLabel currentAtelier = new JLabel("Atelier courant: ");
                titlePanel.add(currentAtelier);

                JLabel picture = new JLabel();
                ImageIcon icon = new ImageIcon(path + "space-01.jpg");
                picture.setIcon(icon);
                picture.setPreferredSize(new Dimension(pictureWpx, pictureHpx));
                centerPanel.add(picture);

                String[] stringOfPieces = { "<choisir piece...>" };

                JLabel labelInfo = new JLabel("Pieces disponibles:");
                comboBoxPieces = new JComboBox(stringOfPieces);
                comboBoxPieces.setSelectedIndex(0);
                comboBoxPieces.addActionListener(this);
                eastPanel.add(labelInfo);
                comboBoxPieces.setEnabled(false);
                eastPanel.add(comboBoxPieces);

                labelInfo = new JLabel("Prix minimum de production:");
                buttonCalcul = new JButton("CALCULER");
                buttonCalcul.addActionListener(this);
                eastPanel.add(labelInfo);
                buttonCalcul.setEnabled(false);
                eastPanel.add(buttonCalcul);
               
               
                buttonLoad = new JButton("Charger...");
                buttonLoad
                                .setToolTipText("Charger description d'un atelier a partir d'un fichier .xml.");
                buttonLoad.addActionListener(this);
               
                buttonClose=new JButton("Fermer...");
                buttonClose
                                .setToolTipText("Fermer description d'un atelier.");
                buttonClose.addActionListener(this);
                buttonClose.setEnabled(false);

                buttonPanel.add(buttonLoad);
                buttonPanel.add(buttonClose);

                myPanel.add(titlePanel, BorderLayout.NORTH);
                myPanel.add(centerPanel, BorderLayout.CENTER);
                myPanel.add(buttonPanel, BorderLayout.SOUTH);
                myPanel.add(eastPanel, BorderLayout.EAST);
                myPanel.add(westPanel, BorderLayout.WEST);

                add(myPanel);
        }

        public void actionPerformed(ActionEvent e) {
                if (e.getActionCommand().equals(buttonLoad.getActionCommand())) {/* appui sur buttonLoad */
                        int returnVal = fc.showOpenDialog(WorkshopGUI.this);
                        if (returnVal == JFileChooser.APPROVE_OPTION) {
                                File file = fc.getSelectedFile();
                                String fileName = file.toString();
                                try {
                                        JOptionPane.showMessageDialog(this, fileName, "Atelier",
                                                        JOptionPane.PLAIN_MESSAGE);
                                } catch (Exception e1) {
                                        JOptionPane.showMessageDialog(this, "Message d'erreur...",
                                                        "Atelier", JOptionPane.ERROR_MESSAGE);
                                        return;
                                }
                               
                               
                                /* chargement fichier xml et preparation affichage atelier */
                               
                                myWorkshop=new Workshop();
                                try {
                                        /* chargement */
                                        SimpleContentHandler.fillWorkshopFromXMLFile(file.getAbsolutePath(), myWorkshop);

                                        /* verification de validite du workshop */
                                        if (myWorkshop.checkWorkshop()){ /* si ok, on peut utiliser */
                                                /* reglages de l'affichage */
                                                        /* modification titre */
                                                titlePanel.removeAll();
                                                titlePanel.add(new JLabel(myWorkshop.getName()));
                                               
                                                        /* Ajout des pieces à la comboBox */
                                                myWorkshop.fillComboBox(comboBoxPieces) ;
                                                        /* modification d'etat des composants */
                                                buttonLoad.setEnabled(false);
                                                buttonClose.setEnabled(true);
                                                comboBoxPieces.setEnabled(true);
                                                buttonCalcul.setEnabled(true);
                                                centerPanel.setVisible(false);
                                                        /* mise a jour affichage infos workshop */
                                                contents.removeAll();
                                                contents.setColumns(50);
                                                contents.setLineWrap(true);
                                                contents.setRows(25);
                                                contents.setWrapStyleWord(true);
                                                myWorkshop.PrintOnPanel(contents);
                                                contents.setEditable(false);
                                                scrollPane = new JScrollPane(contents);
                                                westPanel.add(scrollPane);
                                                westPanel.setVisible(true);
                                        }
                                        else{/* sinon, on utilise pas */
                                                /* on previent l'utilisateur qu'il y a un probleme */
                                                JOptionPane.showMessageDialog(this, new JTextArea("Impossible de charger cet atelier:\nCertaines pieces ne peuvent pas etre fabriquees."), "Atelier",JOptionPane.PLAIN_MESSAGE);
                                        }
                                } catch (SAXException e1) {
                                        e1.printStackTrace();
                                        System.out.println("SAX");
                                        JOptionPane.showMessageDialog(this, new JTextArea("Chargement annulé:\nUn probleme est survenu lors du chargement."), "Atelier",JOptionPane.PLAIN_MESSAGE);
                                } catch (IOException e1) {
                                        e1.printStackTrace();
                                        System.out.println("IO");
                                        JOptionPane.showMessageDialog(this, new JTextArea("Chargement annule:\nUn probleme est survenu lors du chargement."), "Atelier",JOptionPane.PLAIN_MESSAGE);
                                }

                        }
                }
                if (e.getActionCommand().equals(buttonCalcul.getActionCommand())) {/* appui sur buttonCalcul */
                       
                	/* Il faut exclure la cas où la comboBox n'est pas sur une piece mais sur l'invite */
        			if(((String) comboBoxPieces.getSelectedItem()).compareToIgnoreCase("<choisir piece...>")!=0) {
        				try {
        					Process proc = myWorkshop.minPrice((String) comboBoxPieces.getSelectedItem(),"",new ArrayList<String>()) ;
        					JOptionPane.showMessageDialog(this, new JTextArea(proc.toString()), "Atelier",JOptionPane.PLAIN_MESSAGE);
        				} catch(InfiniteLoopException ex) {
        					JOptionPane.showMessageDialog(this, "L'atelier contient des opérations récursives.", "Erreur !", JOptionPane.PLAIN_MESSAGE);
        				}
        			}
                }
                if (e.getActionCommand().equals(buttonClose.getActionCommand())) {/* appui sur buttonClose */
                        westPanel.removeAll();
                        westPanel.setVisible(false);
                        centerPanel.setVisible(true);
                        buttonClose.setEnabled(false);
                        buttonLoad.setEnabled(true);
                        comboBoxPieces.setEnabled(false);
                        comboBoxPieces.removeAllItems();
                        comboBoxPieces.addItem("<choisir piece...>") ;
                        buttonCalcul.setEnabled(false);
                        titlePanel.removeAll();
                        titlePanel.add(new JLabel("Atelier courant: "));
                       
                }
        } // end of function actionPerformed()


        /** Returns an ImageIcon, or null if the path was invalid. */
        protected static ImageIcon createImageIcon(String path) {
                java.net.URL imgURL = WorkshopGUI.class.getResource(path);
                if (imgURL != null) {
                        return new ImageIcon(imgURL);
                } else {
                        System.err.println("Couldn't find file: " + path);
                        return null;
                }
        }

        static private void createAndShowGUI() throws Exception {

                // Create and set up the window.
                JFrame frame = new JFrame("Atelier");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

                // Create and set up the content pane.
                WorkshopGUI newContentPane = new WorkshopGUI();
                newContentPane.setOpaque(true);
                frame.setContentPane(newContentPane);

                Dimension preferredSize = new Dimension(frame.getSize().width, frame
                                .getSize().height);
                frame.setLocation((screenSize.width - preferredSize.width) / 2
                                - (pictureWpx + 100) / 2,
                                (screenSize.height - preferredSize.height) / 2
                                                - (pictureHpx + 100) / 2);

                // Display the window.
                frame.pack();
                frame.setVisible(true);
        }

        public static void main(String[] args) throws Exception {
                createAndShowGUI();
        }
}